package com.webex.ta.hydra.gui.menu;

import com.webex.ta.hydra.core.PropertyManager;
import com.webex.ta.hydra.gui.MenuFactory;

import javax.swing.*;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-30
 * Time: 14:56:52
 */
public class DynamicMenuFactory {
    public static JMenuItem loadMenuItem(String name, boolean setMnemonic) {
        if (name.charAt(0) == '%')
            return loadMenu(name.substring(1));

        return _loadMenuItem(name, setMnemonic);
    }

    public static JMenu loadMenu(String name) {
        return new DynamicMenu(name,
                PropertyManager.getInstance().getProperty(name.concat(".label")));
    }

    private static JMenuItem _loadMenuItem(String name, boolean setMnemonic) {
        PropertyManager propmgr = PropertyManager.getInstance();
        String label = propmgr.getProperty(name + ".label");
        String action = propmgr.getProperty(name + ".action");
        String icon = propmgr.getProperty(name + ".icon.small");

        if (label == null)
            label = name;

        char mnemonic;
        int index = label.indexOf('$');
        if (index != -1 && label.length() - index > 1) {
            mnemonic = Character.toLowerCase(label.charAt(index + 1));
            label = label.substring(0, index).concat(label.substring(++index));
        } else {
            mnemonic = '\0';
        }
        JMenuItem mi;
//        if (PropertyManager.getInstance().getBooleanProperty(name + ".toggle")) {
//            mi = new JCheckBoxMenuItem(label, name);
//        } else {
        mi = MenuFactory.makeMenuItem(label, name, action);
//            mi = new JMenuItem(label, name);
//        }
//        Icon itemIcon = loadIcon(PropertyManager.getInstance().getProperty(name + ".icon.small"));
        if (icon != null)
            mi.setIcon(loadIcon(icon));
        
        return mi;
    }

    private static Icon loadIcon(String icon) {
        try {
            ClassLoader loader = DynamicMenuFactory.class.getClassLoader();
            return new ImageIcon(loader.getResource(icon));
        } catch (Throwable e) {
            return null;
        }
    }
}
